package com.mango.http;

import org.apache.log4j.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {
	public Logger log = Logger.getLogger(getClass());
	private ByteBufToBytes reader;
	@SuppressWarnings("deprecation")
	@Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg){  
        if (msg instanceof HttpRequest) {
        	//httpRequest 头部
            HttpRequest request = (HttpRequest) msg;
            /*
             	DefaultHttpRequest(decodeResult: success, version: HTTP/1.1)
				GET / HTTP/1.1
				Host: localhost:3000
				Connection: keep-alive
				Cache-Control: max-age=0
				Upgrade-Insecure-Requests: 1
				User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
				Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*//*;q=0.8
				Accept-Encoding: gzip, deflate, sdch, br
				Accept-Language: zh-CN,zh;q=0.8
				Cookie: ICITYSession=e3e2295fd5f248179d5710bab87c9add
             */
            String uri = request.getUri();
            log.info("request uri:"+uri);
            if (HttpHeaders.isContentLengthSet(request)) {
                reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(request));  
            }  
        }else if(msg instanceof HttpContent) {  
            HttpContent httpContent = (HttpContent) msg;  
            ByteBuf content = httpContent.content();
            if(reader!=null){
            	reader.reading(content);
            }
            content.release();
            if (reader!=null && reader.isEnd()) {
                String resultStr = new String(reader.readFull());  
                System.out.println("Client said:" + resultStr);  
  
                FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer("I am ok"  
                        .getBytes()));  
                response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");  
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());  
                response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);  
                ctx.write(response);  
                ctx.flush();
                ctx.close();
            }else{
            	FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer("no data"  
                        .getBytes()));  
                response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");  
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());  
                response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);  
                ctx.write(response);  
                ctx.flush();
                ctx.close();
            }
        }  
    }  
  
//    @Override  
//    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {  
//        System.out.println("HttpServerInboundHandler.channelReadComplete");  
//        ctx.flush();  
//    }
//    
//    @Override
//    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
//    	 ctx.executor().schedule(
//                 () -> ctx.fireExceptionCaught(new TimeoutException()), 
//                 15, TimeUnit.SECONDS);
//         super.channelRegistered(ctx);
//    }
}
